package com.hermes.comics.dialogs;

import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;

import android.text.TextUtils;

import android.view.View;

import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;

import com.hermes.comics.R;
import com.hermes.comics.data.Constants;
import com.hermes.comics.data.Serie;
import com.hermes.comics.data.SerieGroup;
import com.hermes.comics.data.SerieTag;

public class EditSerieFieldDialog implements DialogInterface.OnClickListener {

  public static AlertDialog build(Activity activity, SaveItemDialog.OnSaveData onSaveData, Serie serie, SerieTag tag) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle(tag.title());

    EditSerieFieldDialog editSerieField = new EditSerieFieldDialog(activity, onSaveData, serie, tag);

    if (tag == SerieTag.LANGUAGE) {
      return builder
          .setSingleChoiceItems(R.array.language_values, editSerieField.getLanguageIndex(), editSerieField)
          .create();
    }

    return builder.setView(editSerieField.getTextView())
        .setPositiveButton(android.R.string.ok, editSerieField)
        .setNegativeButton(android.R.string.cancel, editSerieField)
        .create();
  }

  private final Activity activity;
  private final Serie serie;
  private final SerieTag tag;
  private final AutoCompleteTextView textView;
  private final SaveItemDialog.OnSaveData onSaveData;

  private EditSerieFieldDialog(Activity activity, SaveItemDialog.OnSaveData onSaveData, Serie serie, SerieTag tag) {
    this.activity = activity;
    this.onSaveData = onSaveData;
    this.serie = serie;
    this.tag = tag;
    this.textView = new AutoCompleteTextView(activity);
    this.textView.setLines(4);

    String value = tag.value(serie);
    if (!TextUtils.isEmpty(value)) {
      this.textView.setText(value.replace("|", "\n"));
    }
  }

  View getTextView() {
    return textView;
  }

  int getLanguageIndex() {
    for (int i = 0; i < Constants.LANGUAGE_VALUES.length; ++i) {
      if (Constants.LANGUAGE_VALUES[i].equals(SerieTag.LANGUAGE.value(serie))) {
        return i;
      }
    }
    return 0;
  }

  @Override
  public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();

    String value = null;
    if (tag == SerieTag.LANGUAGE) {
      value = Constants.LANGUAGE_VALUES[which];
    } else {
      value = textView.getText().toString().replace("\n", "|");
    }

    serie.setTag(tag, value);
    SaveItemDialog.buildForSerie(activity, serie, onSaveData).show();
  }
}
